package data_api

import (
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
	"time"
)

type DateCount struct {
	Date  string `json:"date"`
	Count int    `json:"count"`
}

// DateCountResponse  构造返回数据
type DateCountResponse struct {
	DateList  []string `json:"date_list"`
	LoginDate []int    `json:"login_date"` //登录数据
	SignDate  []int    `json:"sign_date"`  //注册数据
}

// SevenLogin 获取近七天的登录和注册数据
// @Summary 获取近七天的登录和注册数据
// @Tags 数据管理
// @Accept json
// @Produce json
// @Success 200 {string} json "{"code": 0, "message": "请求成功", "data": DateCountResponse}"
// @Failure 500 {string} json "{"code": 2, "message": "服务器内部错误"}"
// @Router /api/data_login [get]
func (DataApi) SevenLogin(c *gin.Context) {
	var loginDateCount, signDateCount []DateCount
	//以下查询语句等价于以下原生sql  查询7天内的数据并统计个数
	//select date_format(created_at,'%Y-%m-%d') as date,count(id) as count from login_data_models where
	// date_sub(curdate(),interval 7 day)<=created_at group by date;
	//查看7天内登录的人数
	global.DB.Model(models.LoginDataModel{}).
		Where("date_sub(curdate(),interval 7 day)<=created_at").
		Select("date_format(created_at,'%Y-%m-%d') as date", "count(id) as count").
		Group("date").
		Scan(&loginDateCount)
	//查询并统计从不同平台注册的用户数
	global.DB.Model(models.UserModel{}).
		Where("date_sub(curdate(),interval 7 day)<=created_at").
		Select("date_format(created_at,'%Y-%m-%d') as date", "count(id) as count").
		Group("date").
		Scan(&signDateCount)
	now := time.Now()
	var LogindateCountMap = map[string]int{}
	var SigndateCountMap = map[string]int{}
	var loginCountList, signCountList []int
	for _, i2 := range loginDateCount {
		LogindateCountMap[i2.Date] = i2.Count
	}
	for _, i2 := range signDateCount {
		SigndateCountMap[i2.Date] = i2.Count
	}
	var dateList []string
	for i := -7; i < 0; i++ {
		day := now.AddDate(0, 0, i).Format("2006-01-02")
		loginCount := LogindateCountMap[day]
		signCount := SigndateCountMap[day]
		dateList = append(dateList, day)
		loginCountList = append(loginCountList, loginCount)
		signCountList = append(signCountList, signCount)
	}
	res.OkWithData(DateCountResponse{
		DateList:  dateList,
		LoginDate: loginCountList,
		SignDate:  signCountList,
	}, c)
}
